package com.zone.mybatis.binding;

import com.zone.mybatis.session.SqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: zongzi
 * @description: TODO
 * @date: 2023/12/13
 */
public class MapperProxy<T> implements InvocationHandler {

    private final Class<T> mapperInterface;
    private final SqlSession sqlSession;

    private final Map<Method, MapperMethod> cacheMethod = new HashMap<>();

    public MapperProxy(Class<T> mapperInterface, SqlSession sqlSession) {
        this.mapperInterface = mapperInterface;
        this.sqlSession = sqlSession;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // Object自带的方法不进行代理
        if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this, args);
        }
        MapperMethod mapperMethod = this.getCacheMethod(method);
        return mapperMethod.execute(sqlSession, args);
    }

    private MapperMethod getCacheMethod(Method method) {
        MapperMethod mapperMethod = cacheMethod.get(method);
        if (mapperMethod == null) {
            mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
            cacheMethod.put(method, mapperMethod);
            return mapperMethod;
        }
        return mapperMethod;
    }
}
